package com.chaoyue.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.chaoyue.base.utils.CollUtils;
import com.chaoyue.base.utils.ObjectUtils;
import com.chaoyue.content.beans.dto.CourseCategoryTreeDto;
import com.chaoyue.content.beans.po.CourseCategory;
import com.chaoyue.content.mapper.CourseCategoryMapper;
import com.chaoyue.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author whr
 */

@SuppressWarnings({"all"})
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    /**
     * @description: 返回树型结构的的数据
     * @param: id
     * @return:List<CourseCategoryTreeDto>
     * @author whr
     * @date: 2024/12/8 18:44
     */
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //调用mapper查询课程分类数据
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //创建新的list封装数据作为返回对象
        List<CourseCategoryTreeDto> treeDtoList = new ArrayList<>();
        //建立idMap
        Map<String, CourseCategoryTreeDto> treeMap = courseCategoryTreeDtos.stream().
                filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //以partentId分组
        Map<String, List<CourseCategoryTreeDto>> prantIdMap = courseCategoryTreeDtos.stream().collect(Collectors.groupingBy(item -> item.getParentid()));
        for (Map.Entry<String, List<CourseCategoryTreeDto>> entry : prantIdMap.entrySet()) {
            String partentId = entry.getKey();
            CourseCategoryTreeDto partent = treeMap.get(partentId);
            if (ObjectUtils.isEmpty(partent)) {
                continue;
            }
            partent.setChildrenTreeNodes(entry.getValue());
            treeDtoList.add(partent);
        }
        return treeDtoList;
    }
}
